/********************************************************************************
 * ItemsServiceDelegator.java
 *
 * Created by Ankur Jain
 * Last modified Date: Aug 26, 2008 11:13:51 AM by Nishan
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/
package com.printeverywhere.delegator;

import static com.printeverywhere.util.AdminConstants.SESSION_CLOSED;
import static com.printeverywhere.util.AttributeConstants.CLOSING_SESSION;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.printeverywhere.dto.AuctionWonlist;
import com.printeverywhere.dto.GeneralCategories;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.ItemsWatchlist;
import com.printeverywhere.dto.Itemtype;
import com.printeverywhere.dto.MyAccountCount;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.HibernateUtil;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SearchListCriteria;
import com.printeverywhere.util.SessionUtil;

/**
 * The Class ItemsServiceDelegator.
 */
public class ItemsServiceDelegator {

	/** The log. */
	private static Logger log = Logger.getLogger(ItemsServiceDelegator.class);

	/**
	 * Gets the list.
	 *
	 * @return the list
	 *
	 * @throws HibernateException the hibernate exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Items> getList() throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Getting list for Bank Account without search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		try {
			Transaction transaction = session.beginTransaction();
			List<Items> list = session.createCriteria(Items.class).list();
			transaction.commit();
			return list;
		} catch (HibernateException e) {
			log.error("Got exception when getting list for Bank Account without search criteria".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}

	public static List<Items> getSoldItems(User user){
		List<Items> list = null;
		try {
			Session session = HibernateUtil.getSession();
			Transaction transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Items.class);
			criteria.add(Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.ONE_NUMBER), Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.TWO_NUMBER), Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.THREE_NUMBER))));
			criteria.add(Restrictions.gt(AttributeConstants.SOLD, AdminConstants.ZERO_NUMBER));
			criteria.add(Restrictions.eq(AttributeConstants.USER_ID, user));
			criteria.add(Expression.lt("endTime", DateUtil.getTodaysDate()));
			list = criteria.list();
		} catch (Exception e) {
			log.error("Sold Items not retrived.".intern());
		}
		return list;
	}

	public static List<Items> getNotSoldItems(User user){
		List<Items> list = null;
		try {
			Session session = HibernateUtil.getSession();
			Transaction transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Items.class);
			criteria.add(Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.ONE_NUMBER), Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.TWO_NUMBER), Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.THREE_NUMBER))));
			criteria.add(Restrictions.eq(AttributeConstants.SOLD, AdminConstants.ZERO_NUMBER));
			criteria.add(Restrictions.eq(AttributeConstants.USER_ID, user));
			criteria.add(Expression.lt("endTime", DateUtil.getTodaysDate()));
			list = criteria.list();
		} catch (Exception e) {
			log.error("Sold Items not retrived.".intern());
		}
		return list;
	}
	public static Items getItemsById(int id) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Getting list for Items by Id".intern());
		}
		Session session = HibernateUtil.getSession();
		try{
			session.beginTransaction();
			Criteria criteria = session.createCriteria(Items.class);
			criteria.add(Restrictions.eq(AttributeConstants.ITEMID , id));
			List<Items> itemslist = criteria.list();
			return ((itemslist.size() > 0) ? itemslist.get(0) : new Items());
		}catch (HibernateException e) {
			log.error("Got exception when getting list for Items by Id".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}

	/**
	 * Gets the list.
	 *
	 * @return the list
	 *
	 * @throws HibernateException the hibernate exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Items> getItemsList(GeneralCategories categories) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Getting list for Bank Account without search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		try {
			Transaction transaction = session.beginTransaction();
			Criteria crit= session.createCriteria(Items.class);
			//crit.add(Restrictions.or(Restrictions.eq("generalCategories", categories), Restrictions.in("generalCategories", categories.getGeneralCategorieses())));
			List<Items> list=crit.list();
			transaction.commit();
			return list;
		} catch (HibernateException e) {
			log.error("Got exception when getting list for Bank Account without search criteria".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			HibernateUtil.closeSession();
		}
	}





	/**
	 * Gets the list.
	 *
	 * @param searchCriteria the search criteria
	 *
	 * @return the list
	 *
	 * @throws HibernateException the hibernate exception
	 */
	public static List<Items> getList(SearchCriteria searchCriteria)throws HibernateException {
		if(log.isInfoEnabled()){
		log.info("Getting list for Items with search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(Items.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);
			criteria.add(Restrictions.eq(key, value));
		}
		Transaction transaction = session.beginTransaction();
		List<Items> list;
		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			log.error("Got exception when getting list for Items with search criteria".intern());
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}

	public static List<Items> getListBySearchListCriteria(SearchListCriteria searchCriteria)throws HibernateException {
		if(log.isInfoEnabled()){
		log.info("Getting list for Items with search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(Items.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object[] value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);
			if (((String) value[1]).equals(SearchListCriteria.EQ)) {
				criteria.add(Restrictions.eq(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GE)) {
				criteria.add(Restrictions.ge(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.GT)) {
				criteria.add(Restrictions.gt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ILIKE)) {
				criteria.add(Restrictions.ilike(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNOTNULL)) {
				criteria.add(Restrictions.isNotNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.ISNULL)) {
				criteria.add(Restrictions.isNull(key));
			} else if (((String) value[1]).equals(SearchListCriteria.LE)) {
				criteria.add(Restrictions.le(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LIKE)) {
				criteria.add(Restrictions.like(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.LT)) {
				criteria.add(Restrictions.lt(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.NE)) {
				criteria.add(Restrictions.ne(key, value[0]));
			} else if (((String) value[1]).equals(SearchListCriteria.IN)) {
				criteria.add(Restrictions.in(key, (Object[]) value[0]));
			}
		}
		Transaction transaction = session.beginTransaction();
		List<Items> list = new ArrayList<Items>();
		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			for (String keyexception : keys) {
				log.info(keys);
			}
			throw e;
		} finally {
			log.info(SESSION_CLOSED);
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}

	public static int getSellingSize(User user, Integer sellingType){
		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute(AdminConstants.ID, sellingType);
		Itemtype itemType = new Itemtype();
		if(CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, Itemtype.class).size()> 0){
			itemType = (Itemtype) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, Itemtype.class).get(AdminConstants.ZERO_NUMBER);
		}
		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute(AdminConstants.USERID , user);
		searchCriteria.setAttribute(AttributeConstants.ITEMTYPE, itemType);
		return ItemsServiceDelegator.getList(searchCriteria).size() > 0?ItemsServiceDelegator.getList(searchCriteria).size() : 0;
	}

	public static void addNote(AuctionWonlist wonlist) throws HibernateException {
		if (log.isInfoEnabled()) {
			log.info("Called addNote method".intern());
		}
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.saveOrUpdate(wonlist);
			tx.commit();
		} catch (RuntimeException e) {
			log.error("Got exception when addNote "
					.intern());
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			if (log.isInfoEnabled()) {
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}

	public static void deleteItems(HttpServletRequest request) throws Exception{
		SearchListCriteria searchListCriteria = new SearchListCriteria();
		try{
			if((request.getParameter("itemId") != null) && (request.getParameter("deleteItem") != null)){
				searchListCriteria.removeAllAttribute();
				searchListCriteria.setAttribute("user.id", new Object[]{SessionUtil.getUser(request).getId() , SearchListCriteria.EQ,});
				searchListCriteria.setAttribute("items.itemId", new Object[]{Integer.parseInt(request.getParameter("itemId")) , SearchListCriteria.EQ,});
				List<ItemsWatchlist> itemlist  = ItemsWatchListServiceDelegator.getList(searchListCriteria);
				ItemsWatchlist itemsWatchlist = (itemlist.size() > 0 ? itemlist.get(0) : null);
				CommonFunctionDelegator.GeneralDelete(itemsWatchlist);
				log.error("Item deleted successfully.");
			}
			else if(request.getParameter("check_list") != null) {
				String[] checkedId = request.getParameterValues("check_list");
				if(request.getParameter("deleteMsg") != null && request.getParameter("deleteMsg").equalsIgnoreCase("delete")){
					for (String chkid : checkedId) {
						searchListCriteria.removeAllAttribute();
						searchListCriteria.setAttribute("user.id", new Object[]{SessionUtil.getUser(request).getId() , SearchListCriteria.EQ,});
						searchListCriteria.setAttribute("items.itemId", new Object[]{Integer.parseInt(chkid) , SearchListCriteria.EQ,});
						List<ItemsWatchlist> itemlist  = ItemsWatchListServiceDelegator.getList(searchListCriteria);
						ItemsWatchlist itemsWatchlist = (itemlist.size() > 0 ? itemlist.get(0) : null);
						if(itemlist!=null){
							CommonFunctionDelegator.GeneralDelete(itemsWatchlist);
							if(request.getParameter("redirectAction") != null || !request.getParameter("redirectAction").equals("")){
								if(request.getParameter("redirectAction").equalsIgnoreCase("myWantedWatchingOthers")){
									MyAccountCount myAccountCount = ((MyAccountCount) request.getSession().getAttribute(AttributeConstants.MYACCOUNTCOUNT));
									if(myAccountCount.getItemWantedWatchingOthers() > 0){
										myAccountCount.setItemWantedWatchingOthers(myAccountCount.getItemWantedWatchingOthers() - 1);
									}
									request.getSession().setAttribute(AttributeConstants.MYACCOUNTCOUNT, myAccountCount);

								}
							}
						}
					}
				}
				log.error("Items deleted successfully.");
			}
		}catch (Exception e) {
			log.error("Error While deleting Items.");
			throw e;
		}
	}


	public static void main(String[] args) {
		/*GeneralCategories categories=CategoryManagerServiceDelegator.get(49);
		System.out.println(getItemsList(categories).size());
		Items items = ItemsServiceDelegator.getItemsById(1);
		System.out.println(items.getTitle());*/
		//System.out.println(getList().size());
		List<Items> list = null;
		try {
			User user = UserServiceDelegator.getUser(1);
			Session session = HibernateUtil.getSession();
			Transaction transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Items.class);
			criteria.add(Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.ONE_NUMBER), Restrictions.or(Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.TWO_NUMBER), Restrictions.eq(AttributeConstants.ITEMTYPE_ID, AdminConstants.THREE_NUMBER))));
			criteria.add(Restrictions.eq(AttributeConstants.SOLD, AdminConstants.ZERO_NUMBER));
			criteria.add(Restrictions.eq(AttributeConstants.USER_ID, user));
			criteria.add(Expression.lt("endTime", DateUtil.getTodaysDate()));
			list = criteria.list();
			System.out.println(list.size());
		} catch (Exception e) {
			log.error("Sold Items not retrived.");
		}
	}


}